package com.leinao.builder;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.leinao.bean.Field;
import com.leinao.config.JDBCConfig;
import com.leinao.logic.SimpleService;
import com.leinao.util.CamelChangeUtil;
import com.leinao.util.CharTransformUtil;
import com.leinao.util.JDKPackUtil;
import com.leinao.util.ReadDirectory;

import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * Title:数据库类型与java类型的相互映射bean
 * Description:
 * @author wangshoufa
 * @date 2019年03月08日
 */
public class BeanBuilder extends Builder {
	private String packageName;
	private String basePath;
	private SimpleService service;
	private String mod;

	public BeanBuilder(JDBCConfig jdbcConfig, String basePath, String packageName,String mod) {
		this.packageName = packageName;
		this.basePath = new File(basePath, "/").getAbsolutePath();
		this.mod = mod;
		service = new SimpleService(jdbcConfig);
	}

	/*
	 * （非 Javadoc）
	 * 
	 * @see com.kiki.jjt.freemark.Builder#build()
	 */
	@Override
	public boolean build() throws TemplateNotFoundException, MalformedTemplateNameException, IOException, TemplateException, SQLException {
		// 配置包名
		// 选择模版
		String templeName = "Bean.ftl";
		// 导入的包
		// 所有属性
		List<String> tablesName = service.getTablesName();
		for (int i = 0; i < tablesName.size(); i++) {
			String entityName = CamelChangeUtil.toCamel(tablesName.get(i),mod);
			List<Field> fields = service.getFieldsByTableName(tablesName.get(i),mod);
			Set<String> importPacks = JDKPackUtil.getPackByFields(fields);
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("fields", fields);
			model.put("importPacks", importPacks);
			model.put("entityName", entityName);
			FreeMarkService.getCfg().setSharedVariable("packageName", packageName + "." + CharTransformUtil.toLowerCaseFirstOne(entityName));
			model.put("tableName", tablesName.get(i));
			work(templeName, model, new File(basePath, CharTransformUtil.toLowerCaseFirstOne(entityName) + "/model").getAbsolutePath(), entityName + ".java");
		}
		// 打印树形结构目录
		ReadDirectory rd = new ReadDirectory();
		rd.printDir(basePath);
		rd.readFile(basePath);
		return true;
	}
}
